<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试转换时间</title>
</head>

<body>
    <input type="text" id="timeInput" value="">
    <span id="timeBox"></span>
</body>
<script>
    let input = document.getElementById('timeInput')
    let timeBox = document.getElementById('timeBox')
    //   let t='2019-01-30 14:06:00'
    function timeTo(t) {
        let nowTime = new Date
        console.log(nowTime.getTime())

        //大概计算出每秒、分、时、天、月、年的时间戳 继而转为n秒前 n分前、n天前、刚刚 几年前
        let perSecond = 1000
        let perMinute = perSecond * 60
        let perHover = perMinute * 60
        let perDay = perHover * 24
        let perMonth = perDay * 30
        let perYear = perMonth * 12
        let dataTime = new Date(t).getTime()
        let chazhi = nowTime - dataTime
        let what = null
        //当t 为非时间戳时候
        let date = new Date(t)
        let y = date.getFullYear();
        let m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let M = date.getMinutes();
        M = M < 10 ? ('0' + M) : M;
        let nowY = new Date().getFullYear()
        let nowm = new Date().getMonth()+1
        let nowD = new Date().getDate()
        console.log(chazhi, '相差的时间戳')
        if (perSecond < chazhi && chazhi < perMinute) { //一分钟以内的显示'刚刚'
            what = '刚刚'

        } else if (chazhi > perMinute && chazhi < perHover) { //一小时内的显示几分钟前
            what = parseInt(chazhi / perMinute) + '分钟前'

        } else if (chazhi > perHover && chazhi < perDay) { //当天的显示当天的 h : m
            if(nowY==y &&nowm==m &&nowD==d){
                what = h + ":" + M
            }else{
                what = '昨天' + h + ":" + M
            }

        } else if (chazhi < perDay*2 &&chazhi>perDay) { //昨天的显示  昨天 h:m
          
            if(nowY!=y ||nowm!=m ||nowD!=d){
                what = '昨天' + h + ":" + M
            }
        } else if (chazhi > perDay * 2 && chazhi < perYear) { //当年的显示 m-d h:m
            if(y==nowY){
                what = m + '-' + d + " " + h + ":" + M
            }else{
                what = y + "-" + m + "-" +d+ " " + h + ":" + M
            }
           
        } else if (chazhi > perYear ||y!=nowY) { //非当年的 显示 y-m-d h:m
            what = y + "-" + m + "-" +d+ " " + h + ":" + M
        }

        console.log(what, '??????????????????????????????')
        return what
    }

    input.addEventListener('blur', function () {
        console.log(input.value, '??????????????')
        timeBox.innerText = timeTo(input.value)


    }, false)
</script>

</html>